import { useUserStore } from "@/stores/userStore";
import axios from "axios";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
const http =  axios.create({
    baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout:5000
    //在线网址
    //https://www.apifox.cn/apidoc/shared-c05cb8d7-e591-4d9c-aff8-11065a0ec1de/api-67132167

});
// axios请求拦截器
// 一般会进行token身份验证等
http.interceptors.request.use(config => {
  const userStore = useUserStore();
  const token = userStore.userInfo.token;
    if(token){
        config.headers.Authorization = `Bearer ${token}`
        //添加token令牌
    }
    return config
  }, e => Promise.reject(e))
  
  // axios响应式拦截器
  // 一般进行错误的统一提示，token失效的处理等
  http.interceptors.response.use(res => res.data, e => {
    //拿到的就是res.data数据，否则就是res.data.data
    ElMessage({type:'error',message:e.response.data.message})
    //统一的错误提示
     //401token失效处理
     const userStore = useUserStore();
     if(e.response.status === 401){
         userStore.clearUserInfo()
         router.push('/login')
     }
    return Promise.reject(e)
  })
  
  
  export default http